package homework;
import java.io.*;

public class Test02 {

    //2.实现字节数组和任何基本类型和引用类型执行的相互转换
    //提示：使用ByteArrayInutStream和ByteArrayOutputStream。
    // 对象 → byte[]
    public static byte[] toByteArray(Object obj) throws IOException {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(obj);
            return baos.toByteArray();
        }
    }

    // byte[] → 对象
    public static Object fromByteArray(byte[] bytes) throws IOException, ClassNotFoundException {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bais)) {
            return ois.readObject();
        }
    }

    public static void main(String[] args) {
        try {
            // ✅ 测试基本类型包装类
            Integer num = 12345;
            byte[] bytes1 = toByteArray(num);
            Integer restoredNum = (Integer) fromByteArray(bytes1);
            System.out.println("Integer 转换: " + num + " → " + restoredNum);

            // ✅ 测试 String（引用类型）
            String str = "Hello, Java IO!";
            byte[] bytes2 = toByteArray(str);
            String restoredStr = (String) fromByteArray(bytes2);
            System.out.println("String 转换: " + str + " → " + restoredStr);

            // ✅ 测试自定义对象（必须 Serializable）
            Person p1 = new Person("Alice", 25);
            byte[] bytes3 = toByteArray(p1);
            Person p2 = (Person) fromByteArray(bytes3);
            System.out.println("Person 转换: " + p1 + " → " + p2);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Person implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    private final String name;
    private final int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}